//
//  BLColumnTitleView.swift
//  BLLiveTelecast
//
//  Created by BigL055 on 16/5/24.
//  Copyright © 2016年 bigL.liveTelecast.com. All rights reserved.
//

import UIKit

class BLColumnTitleView: UIView {
    
    //传递模型
    var columnArray = [BLColumnTitleItem](){
        didSet{
            //设置UI
            configureUI()
        }
    }
    //按钮数组
    lazy var btnArray = [UIButton]()
    //上次选中按钮
    lazy var preBtn : UIButton? = nil
    //按钮指示View
    lazy var positionView : UIView = {
        let positionView = UIView()
        return positionView
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension BLColumnTitleView{
    
    
    func configureUI() {
        
        //按钮指示View
        positionView.backgroundColor = bl_orangeColor
        self.addSubview(positionView)
        
        //设置专题按钮
        for i in 0..<columnArray.count {
            let btn = UIButton(type: .Custom)
            btn.tag = i
            btn.setTitle(columnArray[i].title, forState: .Normal)
            btn.titleLabel?.font = bl_Font_14
            btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
            btn.setTitleColor(UIColor.orangeColor(), forState: .Selected)
            btn.addTarget(self, action: #selector(BLColumnTitleView.btnClick(_:)), forControlEvents: .TouchUpInside)
            if i == 0 {
                btn.selected = true
                preBtn = btn
            }
            
            self.btnArray.append(btn)
            self.addSubview(btn)
        }
        
    }
    
    func btnClick(btn : UIButton) -> () {
        preBtn?.selected = false
        btn.selected = true
        preBtn = btn
        
        UIView.animateWithDuration(0.25) {
            self.positionView.frame.origin.x = btn.frame.origin.x
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        var btnX : CGFloat = 0
        let btnY : CGFloat = 0
        let btnW : CGFloat = self.frame.width / CGFloat(btnArray.count)
        let btnH : CGFloat = self.frame.height
        
        let positionH : CGFloat = 2
        
        positionView.frame = CGRectMake(0, btnH - positionH, btnW, positionH)
        
        for i in 0..<btnArray.count {
            let btn = btnArray[i]
            btnX = btnW * CGFloat(i)
            btn.frame = CGRectMake(btnX, btnY, btnW,btnH)
            self.addSubview(btn)
        }
        
    }
}